#include "RemoteControlService.h"
#include <QDebug>
#include "JKProcessMonitor.h"
#include <QRegularExpression>
#include <QMap>

QMap<int, QString> gCode = {{0, "START TIMER"},
                           {1, "STOP TIMER"}};

RemoteControlService::RemoteControlService(int argc, char **argv)
    : QtService<QCoreApplication>(argc, argv, QStringLiteral("Adb Daemon"))
{
    QString strDesc = QStringLiteral("保持Android debug bridge无线调试不休眠服务。");
    setServiceDescription(strDesc);
    setServiceFlags(QtService::CanBeSuspended);
}

void RemoteControlService::start()
{
    qDebug() << QStringLiteral("服务开始运行.");
    m_pProcess = QSharedPointer<JKProcessMonitor>(new JKProcessMonitor());
}

void RemoteControlService::stop()
{
    qDebug() << QStringLiteral("服务停止运行.");
    if (m_pProcess) {
        m_pProcess->stop();
    }
}

void RemoteControlService::pause()
{
    qDebug() << QStringLiteral("服务暂停运行.");
    if (m_pProcess) {
        m_pProcess->stop();
    }
}

void RemoteControlService::resume()
{
    qDebug() << QStringLiteral("服务恢复运行.");
    if (m_pProcess) {
        m_pProcess->start();
    }
}

void RemoteControlService::processCommand(int code)
{
    if (gCode.contains(code)) {
        qDebug() << QStringLiteral("接收到命令. 命令代码：%1, 含义: %2").arg(code).arg(gCode[code]);
        switch(code) {
        case 0:
            if (m_pProcess) {
                m_pProcess->start();
            }
            break;
        case 1:
            if (m_pProcess) {
                m_pProcess->stop();
            }
            break;
        default:
            ;
        }
    }
    else {
        qDebug() << QStringLiteral("接收到不支持的命令代码：%1").arg(code);
    }

}

void RemoteControlService::killAdbServer()
{
    if (!m_pProcess) return;
    QStringList arguments = QStringList() << "kill-server";
    QByteArray baOutput;
    QString mAdbCommand("D:/Android/Sdk/platform-tools/adb.exe");
    m_pProcess->execute(mAdbCommand, arguments, baOutput);
}


